﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhy.DigitaPlatform.DeviceAccess.Base;
using Zhy.DigitaPlatform.Entities;

namespace Zhy.DigitaPlatform.DeviceAccess.Transfer
{
    /// <summary>
    /// 通讯基类
    /// </summary>
    internal abstract class TransferObject
    {
        public object TUnit { get; set; }

        /// <summary>
        /// 已连接的设备名称
        /// </summary>
        internal List<string> Conditions = new List<string>();
        /// <summary>
        /// 通讯参数配置方法
        /// 端口号、波特率、数据位、校验位、停止位、IP地址、等等。
        /// </summary>
        /// <param name="props"></param>
        /// <returns></returns>
        internal virtual Result Config(List<DevicePropItemEntity> props) => new Result();
        /// <summary>
        /// 连接方法
        /// </summary>
        /// <param name="trycount">重试次数</param>
        /// <returns></returns>
        internal virtual Result Connect(int trycount = 30) => new Result();
        /// <summary>
        /// 串口的发送和读取报文
        /// </summary>
        /// <param name="req">发送的请求报文 </param>
        /// <param name="receiveLen">正常响应报文长度</param>
        /// <param name="errorLen">异常响应报文长度</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        internal virtual Result<List<byte>> SendAndReceived(List<byte> req, int len1, int len2, int timeout) => null;

        /// <summary>
        /// TCP的发送和读取报文
        /// </summary>
        /// <param name="req">发送的请求报文</param>
        /// <param name="len1">头部的报文长度</param>
        /// <param name="timeout">超时时间</param>
        /// <param name="calcLen">计算实际报文长度逻辑-把头部报文传进去，根据头部计算实际报文的长度</param>
        /// <returns></returns>
        internal virtual Result<List<byte>> SendAndReceived(List<byte> req, int len1, int timeout, Func<byte[], int> calcLen = null)
            => new Result<List<byte>>(false, "NULL");

        /// <summary>
        /// 通讯连接状态
        /// </summary>
        internal bool ConnectState { get; set; } = false;
        /// <summary>
        /// 关闭通讯连接
        /// </summary>
        internal virtual Result Close()
        {
            this.ConnectState = false;
            return new Result();
        }
    }
}
